package com.itheima.server.service;

import com.alibaba.fastjson.JSON;
import com.itheima.commons.template.HuanXinTemplate;
import com.itheima.domain.db.Question;
import com.itheima.domain.huanxin.IMessage;
import com.itheima.domain.mongo.RecommendUser;
import com.itheima.domain.db.UserInfo;
import com.itheima.domain.mongo.UserLocationDTO;
import com.itheima.domain.vo.*;
import com.itheima.dubbo.api.*;
import com.itheima.server.interceptor.UserHolder;
import org.apache.commons.lang3.RandomUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author 阿鹏
 * @date 2021/1/26 20:12
 */
@Service
public class TanhuaService {

    @Reference
    private RecommendUserApi recommendUserApi;

    @Reference
    private UserInfoApi userInfoApi;
    @Reference
    private QuestionApi questionApi;
    @Autowired
    private HuanXinTemplate huanXinTemplate;
    @Reference
    private UserLocationApi userLocationApi;
    @Reference
    private UserLikeApi userLikeApi;
    @Reference
    private FriendApi friendApi;
    @Reference
    private BlackListApi blackListApi;


    public ResponseEntity todayBest() {
        Long userId = UserHolder.getUserId();
        RecommendUser recommendUser = recommendUserApi.findMaxScoreRecommendUser(userId);
        if (recommendUser == null) {
            recommendUser = new RecommendUser();
            recommendUser.setUserId(2L);
            recommendUser.setScore(96D);
        }
        UserInfo userInfo = userInfoApi.findById(recommendUser.getUserId());
        RecommendUserVo vo = new RecommendUserVo();
        BeanUtils.copyProperties(userInfo, vo);
        vo.setFateValue(recommendUser.getScore().intValue());
        if (userInfo.getTags() != null) {
            vo.setTags(userInfo.getTags().split(","));
        }
        return ResponseEntity.ok(vo);
    }

    public ResponseEntity findRecommendation(RecommendUserQueryVo queryVo) {
        Long userId = UserHolder.getUserId();
        PageResult<RecommendUser> pageResult = recommendUserApi.recommendUserList(userId, queryVo.getPage(), queryVo.getPagesize());
        List<RecommendUser> userList = pageResult.getItems();
        if (userList == null || userList.size() == 0) {
            userList = new ArrayList<>();
            String ids = "2,3,4,5,6,7,8,9,10,11";
            for (String id : ids.split(",")) {
                RecommendUser recommendUser = new RecommendUser();
                recommendUser.setUserId(Long.valueOf(id));
                recommendUser.setScore(RandomUtils.nextDouble(70, 95));
                userList.add(recommendUser);
            }
            pageResult = new PageResult<>(10, queryVo.getPagesize(), 1, queryVo.getPage(), userList);
        }

        // 构造最终要生成的一部分数据
        List<RecommendUserVo> voList = new ArrayList<>();
        for (RecommendUser recommendUser : pageResult.getItems()) {
            UserInfo userInfo = userInfoApi.findById(recommendUser.getUserId());
            RecommendUserVo recommendUserVo = new RecommendUserVo();
            BeanUtils.copyProperties(userInfo, recommendUserVo);
            if (userInfo.getTags() != null) {
                recommendUserVo.setTags(userInfo.getTags().split(","));
            }
            recommendUserVo.setFateValue(recommendUser.getScore().intValue());
            voList.add(recommendUserVo);
        }

        PageResult<RecommendUserVo> voPageResult = new PageResult<>();
        BeanUtils.copyProperties(pageResult, voPageResult);
        voPageResult.setItems(voList);
        return ResponseEntity.ok(voPageResult);
    }

    public ResponseEntity getPersonalInfo(long userId) {
        Long score = recommendUserApi.findRecommendUserScore(userId, UserHolder.getUserId());

        UserInfo userInfo = userInfoApi.findById(userId);
        RecommendUserVo vo = new RecommendUserVo();
        BeanUtils.copyProperties(userInfo, vo);
        if (userInfo.getTags() != null) {
            vo.setTags(userInfo.getTags().split(","));
        }

        vo.setFateValue(score.intValue());
        return ResponseEntity.ok(vo);
    }

    public ResponseEntity findStrangerQuestions(Long userId) {
        Question question = questionApi.findByUserId(userId);

        if (question == null) {
            return ResponseEntity.ok("爱不爱我?够不够久?会不会走?");
        } else {
            return ResponseEntity.ok(question.getTxt());
        }
    }

    public ResponseEntity replyStrangerQuestions(Long userId, String reply) {
        // 查找当前用户的个人信息
        UserInfo userInfo = userInfoApi.findById(UserHolder.getUserId());

        // 查找目标用户的问题对象
        Question question = questionApi.findByUserId(userId);

        // 构造消息对象
        IMessage iMessage = new IMessage();
        // 当前用户回复的
        iMessage.setUserId(userInfo.getId().toString());
        iMessage.setNickname(userInfo.getNickname());
        iMessage.setStrangerQuestion(question == null ? "爱不爱我?够不够久?会不会走?" : question.getTxt());
        iMessage.setReply(reply);

        String messageJson = JSON.toJSONString(iMessage);
        // 给目标用户的id发,内容为messageJson
        huanXinTemplate.sendMsg(userId.toString(), messageJson);
        return ResponseEntity.ok(null);
    }

    public ResponseEntity searchNear(String gender, Integer distance) {
        List<UserLocationDTO> dtoList = userLocationApi.searchNear(UserHolder.getUserId(), distance);

        List<UserLocationVo> voList = new ArrayList<>();
        for (UserLocationDTO dto : dtoList) {
            if (UserHolder.getUserId().intValue() == dto.getUserId()) {
                continue;
            }

            UserInfo userInfo = userInfoApi.findById(dto.getUserId());
            if (!gender.equals(userInfo.getGender())) {
                continue;
            }

            UserLocationVo vo = new UserLocationVo();
            vo.setUserId(dto.getUserId());
            vo.setNickname(userInfo.getNickname());
            vo.setAvatar(userInfo.getAvatar());

            voList.add(vo);
        }

        return ResponseEntity.ok(voList);
    }

    public ResponseEntity findCards() {
        Long userId = UserHolder.getUserId();
        PageResult<RecommendUser> pageResult = recommendUserApi.recommendUserList(userId, 1, 99);

        List<RecommendUser> recommendUserList = pageResult.getItems();
        if (CollectionUtils.isEmpty(recommendUserList) && recommendUserList.size() < 50) {
            for (long i = 1; i <= 99; i++) {
                RecommendUser recommendUser = new RecommendUser();
                recommendUser.setUserId(i);
                recommendUser.setToUserId(userId);
                recommendUserList.add(recommendUser);
            }
        }

        List<CardVo> voList = new ArrayList<>();
        for (RecommendUser recommendUser : pageResult.getItems()) {
            Long showUserId = recommendUser.getUserId();
            if (showUserId.longValue() != userId && !blackListApi.exists(userId, showUserId) && !userLikeApi.findIfLikeMe(userId,
                    showUserId) && !friendApi.isFriend(userId, showUserId)) {
                CardVo vo = new CardVo();
                UserInfo userInfo = userInfoApi.findById(recommendUser.getUserId());
                BeanUtils.copyProperties(userInfo, vo);
                vo.setTags(userInfo.getTags().split(","));
                voList.add(vo);
            }
        }

        // 打乱顺序
        Collections.shuffle(voList);

        return ResponseEntity.ok(voList);
    }

    public ResponseEntity likeUser(Long likeUserId) {
        Long userId = UserHolder.getUserId();
        userLikeApi.saveLikeUser(userId, likeUserId);

        // 查询喜欢的用户是否喜欢当前用户,粉丝
        if (userLikeApi.findIfLikeMe(likeUserId, userId)) {
            friendApi.addFriend(userId, likeUserId);
            userLikeApi.removeLike(likeUserId, userId);
            userLikeApi.removeLike(userId, likeUserId);
        }

        return ResponseEntity.ok(null);
    }

    public ResponseEntity disLikeUser(Long likeUserId) {
        Long userId = UserHolder.getUserId();
        // 如果我喜欢过这个用户,就删除喜欢 没有必要,因为不展示
        //if (userLikeApi.findIfLikeMe(userId, likeUserId)) {
        //    userLikeApi.delete(userId, likeUserId);
        //}

        // 添加到黑名单,不在展示
        blackListApi.addBlackList(userId, likeUserId);

        return ResponseEntity.ok(null);
    }
}
